require "digest/sha1"



class UsersController < ApplicationController
  skip_before_filter :require_login, :only => [:create]
  
  def create
  
	if (params[:username] =~ /^[A-Za-z0-9_\s]{5,20}$/) == nil
		rtn_json({'error' => 'Please make sure you use an username between 5 and 20 alphanumeric character.'})
		return			
	end

	if (params[:pwd] =~ /^[A-Za-z0-9_\s]{5,20}$/) == nil
		rtn_json({'error' => 'Please make sure you use an password between 5 and 20 alphanumeric character.'})
		return			
	end
	
	if (params[:email] =~ /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/) == nil
		rtn_json({'error' => "Please make sure that you used an valid email address"})
		return			
	end
			
	if (params[:phone_number] =~ /^[0-9]+$/) == nil
		rtn_json({'error' => "Please make sure that the phone number you input contains digits only (no space allowed)"})
		return			
	end

	if params[:company].to_i == 0
		rtn_json({'error' => "Please specify a company"})
		return			
	end
	
	if params[:site].to_i == 0
		rtn_json({'error' => "Please specify a jobsite."})
		return			
	end


	
    salt =(0...10).map{65.+(rand(25)).chr}.join
    @user = User.new(:password_hash => Digest::SHA1.hexdigest(params[:pwd] + salt),
                        :email => params[:email],
                        :username => params[:username],
                        :jobsite_id => params[:site],
                        :company_id => params[:company],
						:phone_number => params[:phone_number],
                        :password_salt => salt)
    @device = @user.devices.new(:phone_number=>params[:phone_number],:active=>1)                        
    if @user.save && @device.save
	  # update device_id to the most recent device
	  @user.update_attribute(:device_id, @device.id)
      rtn_json({'status' => '200'})
    else
      rtn_json({'error' => 'Our apologies, the service could not create your account. Did you choose your jobsite and company?'})
    end
  end
  
  def update


	if (params[:new_username] =~ /^[A-Za-z0-9_\s]{5,20}$/) == nil
		rtn_json({'error' => 'Please make sure you use an username between 5 and 20 alphanumeric character.'})
		return			
	end
	
	if (params[:email] =~ /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/) == nil
		rtn_json({'error' => "Please make sure that you used an valid email address"})
		return			
	end
	
  	if (params[:phone_number] =~ /^[0-9]+$/) == nil
		rtn_json({'error' => "Please make sure that the phone number you input contains digits only (no space allowed)"})
		return			
	end
	
	begin	
		@user = User.find(params[:users_id])
	rescue ActiveRecord::RecordNotFound
		rtn_json({'error' => "User not found."})
		return		  
	end
    
    if @user  
      @user.update_attribute(:email, params[:email]) if params[:email]
  
      @user.update_attribute(:jobsite_id, params[:site]) if params[:site]
      
      @user.update_attribute(:company_id, params[:company]) if params[:company]
      
      @user.update_attribute(:username, params[:new_username]) if params[:new_username]
      
      @user.update_attribute(:phone_number, params[:phone_number]) if params[:phone_number]
      
      @user.update_attribute(:device_id, params[:device_id]) if params[:device_id]
      
      @user.update_attribute(:default_jobsite, params[:default_jobsite]) if params[:default_jobsite] 
      
      @user.save


	  begin	  
		jobsite = Jobsite.find(@user.jobsite_id)		
	  rescue ActiveRecord::RecordNotFound
	    rtn_json({'error' => "Jobsite not found."})
		return		  
	  end
	  
	  begin
        @device = Device.find_by_user_id(@user.id)  
	  rescue ActiveRecord::RecordNotFound
	    rtn_json({'error' => "Device not found."})
		return		  
	  end 
 
      if @device
        rtn_json({'status' => '200', 'username' => @user.username, 'jobsitename' => jobsite.name, 'jobsiteid' => @user.jobsite_id, 'userid' => @user.id, 'deviceid' => @device.id})
      else
        rtn_json({'status' => '200', 'username' => @user.username, 'jobsitename' => jobsite.name, 'jobsiteid' => @user.jobsite_id, 'userid' => @user.id, 'deviceid' => 1})
      end
    else
      rtn_json({'error' => 'Our apologies, the service could not update your account. Did you choose your jobsite and company?'})
    end
  end
  
  def index
    if params[:site]
      @users = User.where(:jobsite_id => params[:jobsite]).order(:jobsite_id)
    else
      @users = User.order(:jobsite_id)
    end
    
    rtn_json(@users)
  end
  
  def show
  
    begin
		@user = User.find(params[:users_id])
	rescue ActiveRecord::RecordNotFound
		rtn_json({'error' => "User not found."})
		return		  
	end 

    if @user
      rtn_json({'email' => @user.email,'site' => @user.jobsite_id,'company' => @user.company_id, 'phone_number' => @user.phone_number, 'device_id' => @user.device_id, 'username' => @user.username})
    else
      rtn_json({'status' => 'Failed, user not found'})
    end
  end
  
  def rtn_json(obj)
    respond_to do |format|
      format.html{render json: obj, :callback => params[:callback]}
      format.json{render json: obj, :callback => params[:callback]}
    end
  end
end
